package com.seven.ssa.job.once;

import cn.hutool.core.collection.CollUtil;
import com.seven.ssa.model.dto.question.QuestionEsDTO;
import com.seven.ssa.model.dto.question.QuestionEsDao;
import com.seven.ssa.model.entity.Question;
import com.seven.ssa.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * P2：全量同步，从题目至ES
 * CommandLineRunner接口，定义单次任务，以全量写入数据
 */
@Component
@Slf4j
public class FullSyncQuestionToEs implements CommandLineRunner {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionEsDao questionEsDao;

    @Override
    public void run(String... args) {
        // 新建题目列表，获取题目
        List<Question> questionList = questionService.list();
        if (CollUtil.isEmpty(questionList)) {
            return;
        }
        // 把题目列表转为 ES 实体类
        List<QuestionEsDTO> questionEsDTOList = questionList.stream()
                .map(QuestionEsDTO::objToDto)
                .collect(Collectors.toList());
        // 分页批量写入到 ES
        final int pageSize = 500;
        int total = questionEsDTOList.size();
        log.info("全量写入，从题目至ES，启动！ total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            log.info("全量写入 from {} to {}", i, Math.min(i + pageSize, total));
            // 注意同步的数据下标不能超过总数据量
            questionEsDao.saveAll(questionEsDTOList.subList(i, Math.min(i + pageSize, total)));
        }
        log.info("全量写入，从题目至ES，结束！ total {}", total);
    }
}
